#!/usr/bin/env python
# -*- coding:utf-8 -*-
import configparser

from bottle import Bottle

from conn.MyLogs import MyLogs
from conn.MyRedisFactory import RedisConfig
from mqtt.MqttSubscriber import Subscriber

mqttAdm = Bottle()

config = configparser.RawConfigParser()
f = r'setting.ini'
config.read(f, encoding='UTF8')
rds_cfg = RedisConfig(host=config['redis']['host'],
                      port=config['redis']['port'],
                      passwd=config['redis']['password'])
rds_conn = RedisConfig.get_pool(rds_cfg)


# 微品mqtt服务
# Vue+ele管理台界面数据接口
class MqttService:
    def __init__(self):
        return

    @staticmethod
    def fetch_device():
        try:
            return [{"deviceId": device} for device in Subscriber.device_id_array]
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)

    @staticmethod
    def listen_device(device_id):
        try:
            # 根据传递的设备ID，向mqtt服务订阅设备数据
            Subscriber.sub_dev_info(device_id=device_id)
            return True
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)

    @staticmethod
    def load_topic(device_id):
        view_array = []
        try:
            # 从REDIS中获取mqtt的话题数据
            _str = config['subscriber']['topic']
            _str = _str.replace("{dName}", device_id)
            _str_key = f'topic:{_str}'
            _num = rds_conn.llen(_str_key)
            print(_num)
            if _num > 10:
                counts = 10
            else:
                counts = _num
            for _index in range(counts):
                print(rds_conn.lindex(_str_key, _index))
                view_array.append(rds_conn.lindex(_str_key, _index))
            return view_array
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
